package br.com.softway.clinica.controller;

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import br.com.softway.clinica.entity.Login;
import br.com.softway.clinica.repository.LoginRepository;

@ManagedBean(name = "loginController")
public class LoginController {

	@Inject
	private Login login;

	@Inject
	private LoginRepository repository;

	public Login getLogin() {
		return this.login;
	}

	public void setLogin(Login login) {
		this.login = login;
	}

	public String doLogin() {
		String usuario = login.getUsername();
		String senha = login.getPassword();

		Login userLogged = this.repository.find(usuario, senha);

		if (userLogged == null) {
			return "login";
		}

		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(false);
		session.setAttribute("username", login.getUsername().toUpperCase());
		return "home";
	}

	public String doLogoff() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(false);
		session.invalidate();
		return "login";
	}
}
